import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../image/model/DataProvider.dart';
import '../model/DownloadModel.dart';
import '../../image/model/_data.dart';
import 'image_preview_event.dart';
import 'image_preview_state.dart';

class ImagePreviewBloc extends Bloc<ImageEvent, ImageState> {
  // static const MethodChannel _image_preview_channel = MethodChannel('com.qimao.reader/imagepreview');
  // 定义变量
  late ImageData imageData;
  late DownloadModel downloadModel;
  late final PageController _pageController;

  ImagePreviewBloc() : super(const ImageState()) {
    downloadModel = DownloadModel();
    on<InitialImageEvent>(_onInitialImage);
    // 监听下载事件
    on<LoadImageEvent>(_onLoadImage);
  }

  _onLoadImage(LoadImageEvent event, Emitter<ImageState> emit) async {
    if (kDebugMode) {
      print("ImagePreview: _onLoadImage,  开始加载: ${event.index}");
    }
    imageData.index = event.index;
    imageData.filePath =
        await downloadModel.getDownloadPath(imageData.bookId, event.url);
    File file = File(imageData.filePath);
    if (file.existsSync()) {
      emit(ImageLoadedState(
          event.index, imageData.filePath, event.imageUrls.length));
    } else {
      if (kDebugMode) {
        print("ImagePreview: _onLoadImage,  图片未下载，去下载: ${event.index}，${imageData.filePath}");
      }
      emit(ImageLoadingState(event.index, event.imageUrls.length));
      try {
        await downloadModel.downloadImage(event.url, imageData.filePath);
        emit(ImageLoadedState(
            event.index, imageData.filePath, event.imageUrls.length));
      } catch (e) {
        emit(
            ImageErrorState(event.index, e.toString(), event.imageUrls.length));
      }
    }
  }

  _onInitialImage(InitialImageEvent event, Emitter<ImageState> emit) async {
    if (kDebugMode) {
      print("ImagePreview: _onInitialImage,  初始化数据");
    }
    emit(ImageInitialState());
    // TODO: 解析路由传参
    imageData = ImageData(
      DataProvider.params,
      "",
      "",
      1,
    );
    _pageController = PageController(initialPage: imageData.index);
    // 发送加载图片事件
    add(LoadImageEvent(
        imageData.index, imageData.urls[imageData.index], imageData.urls));
  }

  switchImage(int index) {
    add(LoadImageEvent(index, imageData.urls[index], imageData.urls));
  }

  saveToGallery() async {
    print("ImagePreview: saveToGallery");
  }

  get pageController => _pageController;
}
